package org.javaforever.cookieshop.controller;

import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.javaforever.cookieshop.domain.PageBean;
import org.javaforever.cookieshop.service.CustOrderService;
import org.javaforever.cookieshop.service.GoodsService;
import org.javaforever.cookieshop.service.TypeService;
import org.javaforever.cookieshop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AdminCustOrderCustController { 
	@Autowired
	protected GoodsService goodsService;
	@Autowired
	protected CustOrderService orderService;
	@Autowired
	protected TypeService typeService;
	@Autowired
	protected UserService userService;
    
    @GetMapping("/admin/order_list")
    public String adminOrderList(@RequestParam(value = "status", defaultValue = "0") Integer status,@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber, Model model) throws Exception{
        if(pageNumber<=0) pageNumber=1;
        PageBean p = orderService.getOrderPage(status,pageNumber);
        if(p.getTotalPage()==0)
        {
            p.setTotalPage(1);
            p.setPageNumber(1);
        }
        else {
            if(pageNumber>=p.getTotalPage()+1)
            {
                p = orderService.getOrderPage(status,pageNumber);
            }
        }
        model.addAttribute("status", status);
        model.addAttribute("p", p);
        return "/admin/order_list";
    }
    
    @GetMapping("/admin/order_delete")
    public String adminCustOrderDelete(@RequestParam(value = "id", required = true) Long id, Model model) throws Exception{   
	    try {
	        orderService.deleteCustOrder(id);
	        return "redirect:/admin/order_list";
	    } catch (FileUploadException e) {
	        e.printStackTrace();
	        return "redirect:/admin/order_list";
	    }
	}
    
    @GetMapping("/admin/order_softdelete")
    public String adminCustOrderSoftDelete(@RequestParam(value = "id", required = true) Long id, Model model) throws Exception{   
	    try {
	        orderService.softDeleteCustOrder(id);
	        return "redirect:/admin/order_list";
	    } catch (FileUploadException e) {
	        e.printStackTrace();
	        return "redirect:/admin/order_list";
	    }
	}
    
    @GetMapping("/admin/order_status")
    public String adminCustOrderSoftDelete(@RequestParam(value = "id", required = true) Long id, @RequestParam(value = "status", required = true) Integer status, Model model) throws Exception{   
		orderService.updateCustOrderStatus(id,status);
        return "redirect:/admin/order_list";
	}	
}
